<template>
  <div>
    <div style="margin-bottom: 10px;" v-if="editable">
      <span style="color: #ff9900">属性名(如胸围,腰围)应在第一列, 尺码名(如L,XL)应在第一行. 不对时请用"行转列"一键切换</span>
    </div>
    <Row style="margin-bottom: 10px;" v-if="editable">
      <Col :span="18">
        <Button type="primary" @click="showSizeTableModal()">输入尺码表</Button>
        <Button type="primary" @click="rowsToColumns()" :disabled="sizeTableData.length==0" style="margin-left: 10px;">行转列</Button>
        <Dropdown placement="bottom-start" @on-click="convertNumbers" style="margin-left: 10px;">
          <Button type="primary">换算<Icon type="ios-arrow-down"></Icon></Button>
          <DropdownMenu slot="list">
            <DropdownItem name="wToC">N*2 (宽度->周长)</DropdownItem>
            <DropdownItem name="inchToCm"> N*2.54 (inch->cm)</DropdownItem>
            <DropdownItem name="jinToKg"> N/2 (斤->kg)</DropdownItem>
          </DropdownMenu>
        </Dropdown>
        <Button type="primary" @click="addRow()" style="margin-left: 10px;">增加一行</Button>
        <Button type="primary" @click="addCol()" style="margin-left: 10px;">增加一列</Button>
        <Button type="primary" @click="showSizeTableTip()" icon="md-help" shape="circle" size="small" style="margin-left: 10px;"></Button>
      </Col>
      <Col :span="6" style="text-align: right;">
        <Button type="error" icon="md-trash" @click="deleteSizeTable()" style="margin-left: 20px;" :disabled="sizeTableRows.length==0">删除整个尺码表</Button>
      </Col>
    </Row>

    <Table :columns="sizeTableColumns" :data="sizeTableData" border :loading="sizeTableLoading"></Table>
    <!-- 尺码表输入框 -->
    <Modal v-model="sizeTableModal.isShow" title="输入尺码表" :mask-closable="false">
      <Input v-model="sizeTableStr" type="textarea" :rows="15"></Input>
      <div slot="footer">
        <Button @click="hideSizeTableModal()">取消</Button>
        <Button type="primary" icon="md-repeat" @click="transformSizeTable()">转换</Button>
      </div>
    </Modal>

    <!-- 尺码输入说明 -->
    <Modal v-model="sizeTableTipModal.isShow" title="输入格式说明" mask-closable footer-hide>
      <span style="padding-bottom: 0.5rem">
        暂不支持传图片,需要采集人员将图片的尺码表转化为文字模式进行录入. 我们提供了从 excel 等格式粘贴复制的功能.<br/>
      </span>
      <Divider size="small">从Excel复制的表格数据示例</Divider>
      <div>
        <pre>
          尺码(CM)	M	L	XL	2XL	3XL
          胸围	88	94	100	106	112
          腰围	68	74	80	86	92
          肩宽	37	38	39	40	41
          袖长	58	59	60	61	62
          裙长	115	116	117	118	119
        </pre>
      </div>
      <Divider size="small">从<a href="https://web.baimiaoapp.com/image-to-excel" target="_blank">白描网站</a>复制的表格数据示例</Divider>
      <div>
        <pre>
          尺码(CM),M,L,XL,2XL,3XL
          胸围,88,94,100,106,112
          腰围,68,74,80,86,92
          肩宽,37,38,39,40,41
          袖长,58,59,60,61,62
          裙长,115,116,117,118,119
        </pre>
      </div>
      <Divider size="small"><a href="https://ai.youdao.com/product-ocr-table.s" target="_blank">有道识别</a></Divider>
    </Modal>
  </div>
</template>

<script>
import productData from "../js/product/productData";
import {isEmpty, isNotEmpty} from "../../js/commonUtils";

export default {
  name: "SizeTableTransform",
  props: {
    sizeTableRows: {
      type: Array,
      default: function (){
        return []
      }
    },
    editable: {type: Boolean, default: true}
  },
  model: {
    prop: "sizeTableRows",
    event: "change",
  },
  data() {
    return {
      sizeTableModal: {
        isShow: false,
      },
      sizeTableTipModal: {
        isShow: false,
      },
      sizeTableStr: "",
      sizeTableLoading: false,
      selectedIndexList: [],
      sizeFilters: [
        {key:'单位重量',value:'Gross Weight'},
        {key:'产品体积',value:'体积'},
        {key:'主面料成分的含量',value:'Material Ingredients'},
        {key:"主面料成分2的含量",value:'Material 2 Ingredients'},
        {key:'裤脚口款式',value:'Pants Opening Type'},
        {key:'外套材质,面料名称',value:'Material'},
        {key:'属性',value:'Description'},
        {key:'筒高',value:'Boot Height'},
        {key:'鞋跟高度,后跟高',value:'Heel Height'},
        {key:'箱包潮流款式',value:'Bag Type'},
        {key:'款式',value:'Type'},
        {key:'设计细节,款式细节,设计特色',value:'Design Details'},
        {key:'领型，领口形状',value:'Neckline'},
        {key:'袖长,上衣袖长',value:'Sleeve Length'},
        {key:'裤长,衣长,裙长,周长,长度(CM)',value:'Length'},
        {key:'腰型,裤腰',value:'Waistline'},
        {key:'适用性别,性别',value:'Gender'},
        {key:'风格,风格类型',value:'Style'},
        {key:'里料质地,内里材质',value:'Lining Material'},
        {key:'镜片材料,镜片材质',value:'Lens Material'},
        {key:'面料,面料质地,主面料',value:'Fabric'},
        {key:'开盖方式,扣合方式,闭合款式',value:'Closure Type'},
        {key:'鞋头形状,鞋头款式',value:'Toe'},
        {key:'胸围',value:'BUST(cm)'},
        {key:'长度,衣长',value:'LENGTH(cm)'},
        {key:'裤长,裙长',value:'BOTTOM LENGTH(cm)'},
        {key:'肩宽',value:'SHOULDER(cm)'},
        {key:'袖长',value:'SLEEVE(cm)'},
        {key:'腰围',value:'WAIST(cm)'},
        {key:'臀围',value:'HIP(cm)'},
        {key:'身高',value:'SUGGEST HEIGHT(cm)'},
        {key:'体重',value:'SUGGEST WEIGHT(kg)'},
        {key:'码数,尺码,尺寸',value:'SIZE'},
        {key:'年龄',value:'SUGGEST AGE'},
        {key:'档深',value:'CROTCH DEEP(cm)'},
        {key:'摆围',value:'HEM (cm)'},
        {key:'前档',value:'FRONT RISE(cm)'},
        {key:'后档',value:'BACK RISE(cm)'},
        {key:'腿围',value:'THIGH(cm)'},
      ]
    }
  },
  computed: {
    sizeTableColumns() {
      let self = this;
      let columns = [];
      if(self.sizeTableRows.length > 0) {
        let firstRow = this.sizeTableRows[0];
        columns.push({width: 60, align: "center", render(h, params) {
            return params.index==0?"":h("div", [
              h("Checkbox", {
                on: {
                  "on-change": function(flag) {
                    if(flag) {
                      self.selectedIndexList.push(params.index);
                    }else{
                      let index = self.selectedIndexList.findIndex(element => element == params.index);
                      self.selectedIndexList.splice(index, 1);
                    }
                  }
                }
              })
            ])
          }
        });
        for(let i=0; i<firstRow.length; i++) {
          columns.push({key: "column_"+i, width: i==0?220:120, align: "center",
            render(h, params) {
              return h("Input", {
                props: {type: "text", value: params.row["column_"+i]},
                on: {
                  "on-change" : (event) => {
                    self.sizeTableRows[params.index][i] = event.target.value;
                  }
                }
              })
            },
            renderHeader(h, params) {
              return h("div", [
                h("span", "第"+(i+1)+"列"),
                i==0?"":h("a", {
                  props: {href: "javascript: void(0)"},
                  style: {marginLeft: "5px"},
                  on: {
                    click() {
                      self.deleteColumn(i);
                    }
                  }
                }, "删除")
              ]);
            },
          });
        }
        columns.push({title: "操作", width: 150, align: "center", render(h, params) {
            return params.index==0?"":h("div", [
              h("Button", {
                props: {size: "small", icon: "md-trash"},
                on: {
                  click() {
                    self.deleteRow(params.index);
                  }
                }
              }, "删除"),
            ]);
          }
        });
        return columns;
      }
      return columns;
    },
    sizeTableData() {
      if(this.sizeTableRows.length>0) {
        let rows = [];
        for(let i=0; i<this.sizeTableRows.length; i++) {
          let rowData = this.sizeTableRows[i];
          let row = {};
          for(let j=0; j<rowData.length; j++) {
            let cell = rowData[j];
            row["column_"+j] = cell;
          }
          rows.push(row);
        }
        return rows;
      }
      return [];
    },
  },
  methods: {
    showSizeTableModal() {
      this.sizeTableStr = "";
      this.sizeTableModal.isShow = true;
    },
    hideSizeTableModal() {
      this.sizeTableModal.isShow = false;
    },
    showSizeTableTip() {
      this.sizeTableTipModal.isShow = true;
    },
    hideSizeTableTip() {
      this.sizeTableTipModal.isShow = false;
    },
    deleteSizeTable() {
      let self = this;
      self.$Modal.confirm({
        title: "确认",
        content: "确定要删除尺码表吗？",
        okText: "删除",
        onOk() {
          self.sizeTableRows.splice(0);
        }
      });
    },
    transformSizeTable() {
      this.sizeTableModal.isShow = false;
      //有逗号分隔
      if(this.sizeTableStr.indexOf(",") > 0) {
        this.transformSizeTableFromWeb();
      }else{//无逗号分隔
        this.transformSizeTableFromExcel();
      }
    },
    transformSizeTableFromWeb() {
      let rows = this.sizeTableStr.split("\n");
      let data = [];
      for(let i=0; i<rows.length; i++) {
        let row = rows[i];
        if(isNotEmpty(row)) {
          let cells = row.split(",");
          for(let j=0; j<cells.length; j++) {
            cells[j] = cells[j].trim().replace(/^\"/g, "").replace(/\"$/g, "");
            if(isEmpty(cells[j])) {
              cells[j] = " ";
            }
          }
          data.push(cells);
        }
      }
      this.translateSizeTable(data);
    },
    transformSizeTableFromExcel() {
      let rows = this.sizeTableStr.split("\n");
      let data = [];
      for(let i=0; i<rows.length; i++) {
        let row = rows[i];
        let cells = row.split("\t");
        for(let j=0; j<cells.length; j++) {
          cells[j] = cells[j].trim();
          if(isEmpty(cells[j])) {
            cells[j] = " ";
          }
        }
        data.push(cells);
      }
      this.translateSizeTable(data);
    },
    translateSizeTable(data) {
      if(data.length > 0) {
        let filteredData = this.filterData(data);
        let params = {data: filteredData};
        this.sizeTableLoading = true;
        this.$apiImpProduct.translateSizeTable(params).then(response => {
          this.sizeTableLoading = false;
          this.sizeTableRows.splice(0);
          if(response.success) {
            this.sizeTableRows.push(...response.result);
          }else{
            this.$Message.error(response.errorMessage);
          }
        });
      }
    },
    deleteRow(index) {
      let self = this;
      self.$Modal.confirm({
        content: "确定要删除此行吗？",
        onOk() {
          self.sizeTableRows.splice(index, 1);
        }
      })
    },
    deleteColumn(index) {
      let self = this;
      self.$Modal.confirm({
        content: "确定要删除此列吗？",
        onOk() {
          for(let row of self.sizeTableRows) {
            row.splice(index, 1);
          }
        }
      })
    },
    rowsToColumns() {
      let rowsNum = this.sizeTableRows.length; //行数
      let colsNum = this.sizeTableRows[0].length; //列数
      //转换
      let tmpSizeTableRows = [];
      for(let i=0; i<colsNum; i++) { //行数变为列数
        let row = [];
        for(let j=0; j<rowsNum; j++) {
          row.push(this.sizeTableRows[j][i]);
        }
        tmpSizeTableRows.push(row);
      }
      //替换数据
      this.sizeTableRows.splice(0);
      this.sizeTableRows.push(...tmpSizeTableRows);
    },
    convertNumbers(name) {
      if(this.selectedIndexList.length == 0) {
        this.$Message.error("请选择要转换的数据行");
        return;
      }
      switch(name) {
        case "wToC": //宽度转周长
          this.widthToCircle();
          break;
        case "inchToCm":
          this.inchToCm();
          break;
        case "jinToKg":
          this.jinToKg();
          break;
      }
    },
    addRow() {
      let row = [];
      let cols = this.sizeTableRows[0].length;
      for(let i=0; i<cols; i++) {
        row.push("");
      }
      this.sizeTableRows.push(row);
    },
    addCol() {
      for(let i=0; i<this.sizeTableRows.length; i++) {
        this.sizeTableRows[i].push("");
      }
    },
    // mulNum(arg1, arg2) {
    //   let r1 = Number(arg1.toString().replace(".", ""));
    //   let r2 = Number(arg2.toString().replace(".", ""));
    //   let m = 0;
    //
    //   try {
    //     m += arg1.toString().split(".")[1].length;
    //   } catch (e) {
    //     m += 0;
    //   }
    //
    //   try {
    //     m += arg2.toString().split(".")[1].length;
    //   } catch (e) {
    //     m += 0;
    //   }
    //   let result = (r1 * r2) / Math.pow(10, m);
    //   return result;
    // },
    mulNum(arg1,arg2) {
      let r1 = Number(arg1.toString().replace(".", ""))+150;

      return (r1/6.7).toFixed(1);
    },
    isNumber(val) {
      if(isEmpty(val)) {
        return false;
      }
      return !isNaN(val);
    },
    extractCompute(cell, param, fixed) {//提取字符串中的数字，进行换算后，再替换回原字符串
      let numReg = /\d+(\.\d+)?/;
      if(!numReg.test(cell)) { //单元格字符串不含数字,无需换算
        return cell;
      }
      let numArr = cell.match(/\d+(\.\d+)?/g); //将单元格字符串的数字部分提取出来
      let placeholder = "{{*_*}}";//占位符
      cell = cell.replaceAll(numReg, placeholder); //将单元格字符串数字部分以占位符替换掉，数字换算完成后再替换回来
      //换算并替换
      for(let i=0; i<numArr.length; i++) {
        let newNum = this.mulNum(numArr[i], param).toFixed(fixed);
        cell = cell.replace(placeholder, newNum);
      }
      return cell;
    },
    convertCompute(param, fixed) {
      for(let i=0; i<this.selectedIndexList.length; i++) {
        let index = this.selectedIndexList[i];
        let row = this.sizeTableRows[index];
        let newRow = [];
        for(let j=0; j<row.length; j++) {
          if(j == 0) {//第一列不换算
            newRow.push(row[j]);
          }else{
            if(this.isNumber(row[j])) {//如果是数字
              newRow.push(this.mulNum(row[j], param).toFixed(fixed));
            }else{
              let newCell = this.extractCompute(row[j], param, fixed);
              newRow.push(newCell);
            }
          }
        }
        this.sizeTableRows.splice(index, 1, newRow);
      }
    },
    widthToCircle() {
      let param = 2;
      let fixed = 0;
      this.convertCompute(param, fixed);
    },
    inchToCm() {
      let param = 2.54;
      let fixed = 0;
      this.convertCompute(param, fixed);
    },
    jinToKg() {
      let param = 0.5;
      let fixed = 0;
      this.convertCompute(param, fixed);
    },
    filterData(data) {
      for(let i=0; i<data.length; i++) {
        let row = data[i];
        if(i == 0) {
          for(let j=0; j<row.length; j++) {
            row[j] = this.filterSizeName(row[j]);
          }
        }else{
          row[0] = this.filterSizeName(row[0]);
        }
      }
      return data;
    },
    filterSizeName(attrKey) {
      let result = attrKey;
      for (let i = 0; i < this.sizeFilters.length; i++) {
        if (this.sizeFilters[i].key.split( ',' ).includes(attrKey.toLowerCase())){
          result = this.sizeFilters[i].value;
        }
      }
      return result;
    }
  },
  watch: {
    sizeTableRows() {
      this.selectedIndexList.splice(0);
    }
  }
}
</script>

<style scoped>

</style>
